<template>
  <div class="flex">
    <aside class="sidebar" :style="{marginLeft: $store.getters.sidebar.opened ? '250px': '54px'}">
      <ul>
        <li v-for="item in contents" :key="item.path">
          <router-link class="sidebar-link" :to="item.path">{{ item.title }}</router-link>
          <ul v-if="$route.params.name === item.name" class="sidebar-sub-headers">
            <li v-for="nav in navs" :key="nav.title">
              <a class="sidebar-link" @click.prevent="() => scrollToTitle(nav.id)">{{ nav.title }}</a>
            </li>
          </ul>
        </li>
      </ul>
    </aside>

    <router-view :content="article" :toc="subToc" />
  </div>
</template>

<script>
import { marked } from 'marked'
import axios from 'axios'
import { scrollToTargetAdjusted } from '@/utils/index'
const requireAll = (requireContext) => requireContext.keys()

const req = require.context('@document/en', true, /\.md$/)

const fileNames = requireAll(req).map(path => path.replace(/(^\.\/)|(\.md)/g, ''))

console.log(fileNames)

export default {
  data() {
    return {
      article: '',
      navs: [],
      subToc: [],
      index: 0,
      contents: fileNames.map(name => ({ path: `/parameter/document/${name}`, name, title: name }))
    }
  },
  computed: {
    locale() {
      return this.$i18n.locale === 'zh-CN' ? 'zh' : 'en'
    }
  },
  watch: {
    '$route.params.name': {
      immediate: true,
      handler() {
        const dir = this.$i18n.locale === 'zh-CN' ? 'zh' : 'en'
        axios
          .get(`/operator/document/${dir}/${this.$route.params.name}.md`)
          .then((data) => {
            this.navs = []
            this.subToc = []
            this.article = marked.parse(data.data)
          })
      }
    },
    '$i18n.locale': {
      handler() {
        const dir = this.$i18n.locale === 'zh-CN' ? 'zh' : 'en'
        axios
          .get(`/operator/document/${dir}/${this.$route.params.name}.md`)
          .then((data) => {
            this.navs = []
            this.subToc = []
            this.article = marked.parse(data.data)
          })
      }
    }
  },
  mounted() {
    this.initMarked()
  },
  methods: {
    initMarked() {
      const mdRenderer = new marked.Renderer()
      const that = this
      mdRenderer.heading = function(text, level) {
        const escapedText = text.toLowerCase().replace(/\./g, '')

        if (level >= 1) {
          that.subToc.push({
            id: escapedText,
            level: level,
            label: text
          })
          if (level === 2) {
            that.navs.push({ title: text, level, id: escapedText })
          }
        }

        return `
            <h${level} id="${escapedText}">
              <a name="${escapedText}" class="anchor" href="#${escapedText}">
                <span class="header-link"></span>
              </a>
              ${text}
            </h${level}>`
      }

      mdRenderer.image = function(href, title, text) {
        let target = String(href)
        target = target.replaceAll('\\', '/')
        return `<img src="${import.meta.env.VITE_APP_BASE_API}/resource/images/document/${that.locale}/${target}" alt="${text}"/>`
      }

      marked.use({ renderer: mdRenderer })
    },
    scrollToTitle(id) {
      scrollToTargetAdjusted(id, 60)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.sidebar {
  padding: 1.5rem 0;
  font-size: 16px;
  background-color: #fff;
  width: 20rem;
  position: fixed;
  margin: 0;
  top: 60px;
  left: 0;
  min-height: 100vh;
  bottom: 0;
  box-sizing: border-box;
  border-right: 1px solid #eaecef;
  overflow-y: auto;
  .sidebar-sub-headers {
    padding-left: 1rem;
    font-size: .95em;
    a.sidebar-link {
      padding-top: 0.25rem;
      padding-bottom: 0.25rem;
      border-left: none;
    }
  }
  .sidebar-link {
    padding-left: 2rem;
  }
  a {
    display: inline-block;
    &.sidebar-link {
      font-size: 1em;
      font-weight: 400;
      display: inline-block;
      color: #2c3e50;
      border-left: 0.25rem solid transparent;
      padding: 0.35rem 1rem 0.35rem 1.25rem;
      line-height: 1.4;
      width: 100%;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      &.router-link-active {
        font-weight: 600;
        color: #409eff;
        border-left-color: #409eff;
      }
    }
  }
}

.sub-toc {
  font-size: 14px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial,
    sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';
  color: #606266;
  padding: 8px;
  cursor: pointer;
}
.sub-toc:hover {
  color: #0969da;
}

.md-sidebar {
  position: sticky;
  width: 320px;
  top: 124px;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: 1;
  padding: 20px;
  padding-left: 10px;
  border-right: 1px solid #d1d5db;
  height: calc(100vh - 65px);
}

.md-subtoc {
  position: sticky;
  min-width: 300px;
  top: 124px;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: 1;
  padding: 20px 10px 20px 5px;
  border-left: 1px solid #d1d5db;
  height: calc(100vh - 65px);
}
.md-subtoc > .scrollbar,
.md-sidebar > .scrollbar {
  height: calc(100vh - 100px);
}
</style>

<style>
.markdown-body ol {
  list-style: decimal;
}

.markdown-body ul {
  list-style: disc;
}
</style>
